package com.java.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author jl
 * Created on 2020/9/27
 */
public class GroupChatClient {

    private static final String HOST = "127.0.0.1";

    private static final int PORT = 6667;

    private Selector selector;

    private SocketChannel socketChannel;

    private String username;

    public GroupChatClient() {
        try {
            this.selector = Selector.open();
            this.socketChannel = socketChannel.open(new InetSocketAddress(HOST, PORT));
            this.socketChannel.configureBlocking(false);
            this.socketChannel.register(selector, SelectionKey.OP_READ);
            this.username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(this.username + " is ok");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 发送消息
    private void sendMessage(String message) {
        message = this.username + "说:" + message;
        ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBytes());
        try {
            socketChannel.write(byteBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取消息
    private void readMessage() {
        try {
            int select = selector.select();
            if (select > 0) {
                Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                while (keyIterator.hasNext()) {
                    SelectionKey key = keyIterator.next();

                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        channel.read(byteBuffer);
                        String msg = new String(byteBuffer.array());
                        System.out.println(msg.trim());
                    }
                    //当前的key删除，防止重复处理
                    keyIterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        GroupChatClient groupChatClient = new GroupChatClient();
        System.out.println(groupChatClient.selector);
        // 启动一个线程,每隔3秒从服务器读取消息
        new Thread(() -> {
            while (true) {
                groupChatClient.readMessage();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            groupChatClient.sendMessage(msg);
        }
    }

}
